import { useState, useEffect, useRef } from 'react';
import { Button, Space, Modal, Form, Checkbox, Input, InputNumber, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import request from '@/utils/request';
import { WhseSelect, WhseBinSelect } from '@/components/FormItemSelect';
import ItemSelect from '@/components/ItemSelect';
import moment from 'moment';
import QuerySelect from '@/components/QuerySelect';

const { confirm } = Modal;
const apiURL = '/api/services/app/RcvDtl/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>({});
  const [freshNum, setFreshNum] = useState(1);
  const [maxQty, setMaxQty] = useState(999999);
  const [params, setParams] = useState({ whse: 'WGJ' });
  const [wType, setWType] = useState('InspWhse');
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    props.onRef(this);
    if (props.data) {
      setData(props.data);
      formRef.current.setFieldsValue({ model: props.data });
    }
  }, [props.data]);

  const onFinish = (values: any) => {
    save(values.model);
  };

  const save = (model: any) => {
    let act = 'New';
    const method = 'POST';
    if (model.id) {
      act = 'Modify';
    }
    setLoading(true);
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'save.success' }));
          props.refreshData(model.packSlip);
        }
        setLoading(false);
      }
    });
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete?' }),
      onOk() {
        request(apiURL + 'DelBatch', {
          method: 'POST',
          data: [data.id],
        }).then((response) => {
          props.refreshData(data.packSlip);
        });
      },
    });
  };

  const setCurrent = (item: any) => {
    const model = {
      poNum: item.PONum,
      poLine: item.POLine,
      poRelNum: item.PORelNum,
      partNum: item.PartNum,
      partDescription: item.PartDescription,
      ium: item.IUM,
      ourQty: item.RelQty,
      vendorUnitCost: item.UnitCost,
    };
    setMaxQty(item.relQty);
    formRef.current.setFieldsValue({ model });
  };

  const setCurrentJob = (item: any) => {
    const model = {
      jobNum: item.jobNum,
      assemblySeq: item.assemblySeq ? item.assemblySeq : 0,
      jobSeq: item.mtlSeq ? item.mtlSeq : 0,
      partNum: item.partNum,
      partDescription: item.partDescription,
      ium: item.ium,
      ourQty: item.prodQty,
    };
    setMaxQty(item.prodQty);
    formRef.current.setFieldsValue({ model });
  };

  const setCurrentSO = (item: any) => {
    const model = {
      orderNum: item.OrderNum,
      orderLine: item.OrderLine,
      orderRelNum: item.OrderRelNum,
      partNum: item.PartNum,
      partDescription: item.PartDescription,
      ium: item.IUM,
      ourQty: item.OurReqQty,
    };
    setMaxQty(item.OurReqQty);
    formRef.current.setFieldsValue({ model });
  };

  const setCurrentDMR = (item: any) => {
    const model = {
      conNum: item.ConNum,
      conLine: item.ConLine,
      partNum: item.PartNum,
      partDescription: item.PartDescription,
      ium: item.IUM,
      ourQty: item.Quantity,
    };
    setMaxQty(item.Quantity);
    formRef.current.setFieldsValue({ model });
  };

  const setCurrentPart = (part?: any) => {
    if (part) {
      const model: any = {};
      model.partNum = part.PartNum;
      model.partDescription = part.PartDescription;
      model.ium = part.IUM;
      formRef.current.setFieldsValue({ model });
    }
  };

  const selectBin = (e: any) => {
    setFreshNum(freshNum + 1);
    setParams({ whse: e });
  };

  const changeInsp = (e: any) => {
    const whse = e.target.checked ? 'DJK' : 'WGJ';
    setFreshNum(freshNum + 1);
    setWType(e.target.checked ? 'InspWhse' : 'PassedWhse');
    setParams({ whse });
    formRef.current.setFieldsValue({
      model: {
        warehouseCode: whse,
        binNum: '1',
      },
    });
  };

  const createLotNum = () => {
    const datas = formRef.current.getFieldsValue();
    const model = datas.model;
    const dataStr = moment(new Date()).format('YYMMDDhh');
    model.lotNum = 'U-0';
    if (model.receiptType === 'MTL') {
      model.lotNum = 'M-' + model.poNum + '-' + model.poLine + '-' + model.poRelNum;
    } else if (model.receiptType === 'JOB') {
      model.lotNum = 'J-' + model.jobNum + '-' + model.assemblySeq + '-' + model.jobSeq;
    } else if (model.receiptType === 'SO') {
      model.lotNum = 'S-' + model.orderNum + '-' + model.orderLine + '-' + model.orderRelNum;
    }
    model.lotNum = dataStr + '-' + model.lotNum;
    formRef.current.setFieldsValue({ model });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const columnJobItem = [
    {
      title: <FormattedMessage id="pages.jobNum" />,
      dataIndex: 'jobNum',
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
    },
    {
      title: <FormattedMessage id="pages.prodQty" />,
      dataIndex: 'prodQty',
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
    },
  ];

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Form.Item name={['model', 'id']} hidden={true}>
        <Input />
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.packSlip" />}
        name={['model', 'packSlip']}
        rules={[{ required: true }]}
      >
        <Input disabled />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.packLine" />} style={{ marginBottom: 0 }}>
        <Input.Group compact>
          <Form.Item name={['model', 'packLine']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item name={['model', 'receiptType']}>
            <Input disabled />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.poNum" />}
        hidden={!(props.data?.receiptType == 'MTL' || props.data?.receiptType == 'SUB')}
      >
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'poNum']}>
            <Input style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle name={['model', 'poLine']}>
            <InputNumber style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle name={['model', 'poRelNum']}>
            <InputNumber style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle>
            <QuerySelect
              width={780}
              sysReportName="ReportPORel"
              text={<FormattedMessage id="pages.select" />}
              title={<FormattedMessage id="pages.poNum" />}
              btntype="primary"
              setCurrent={setCurrent}
              scroll={{ x: 'max-content', y: '200px' }}
              search={{
                filterType: 'light',
              }}
              params={{
                OpenOrder: 1,
                Approve: 1,
                ApprovalStatus: 'A',
                TranType: props.data?.receiptType,
                OpenRelease: 1,
              }}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.conNum" />}
        hidden={props.data?.receiptType != 'DMR'}
      >
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'conNum']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item noStyle name={['model', 'conLine']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item noStyle>
            <QuerySelect
              width={780}
              sysReportName="NonConfSearch"
              text={<FormattedMessage id="select" />}
              title={<FormattedMessage id="search" />}
              btntype="primary"
              setCurrent={(e: any) => setCurrentDMR(e)}
              scroll={{ x: 'max-content', y: '200px' }}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.jobNum" />}
        hidden={props.data?.receiptType != 'JOB'}
      >
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'jobNum']}>
            <Input style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle name={['model', 'assemblySeq']}>
            <InputNumber style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle name={['model', 'jobSeq']}>
            <InputNumber style={{ width: 80 }} />
          </Form.Item>
          <Form.Item noStyle>
            <ItemSelect
              width={780}
              control="JobHead"
              columns={columnJobItem}
              text={<FormattedMessage id="pages.select" />}
              title={<FormattedMessage id="pages.jobMtl" />}
              act="GetList?completed=1"
              btntype="primary"
              setCurrent={setCurrentJob}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.orderNum" />}
        hidden={props.data?.receiptType != 'SO'}
      >
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'orderNum']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item noStyle name={['model', 'orderLine']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item noStyle name={['model', 'orderRelNum']}>
            <InputNumber disabled />
          </Form.Item>
          <Form.Item noStyle>
            <QuerySelect
              width={780}
              sysReportName="SoSearch"
              text={<FormattedMessage id="pages.select" />}
              title={<FormattedMessage id="pages.orderNum" />}
              btntype="primary"
              setCurrent={setCurrentSO}
              scroll={{ x: 'max-content', y: '200px' }}
              params={{
                OpenOrder: 0,
                VoidOrder: 0,
                Approve: 1,
                OpenRelease: 0,
              }}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.partNum" />} required>
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'partNum']} rules={[{ required: true, message: intl.formatMessage({id: 'pages.partNum.required'}) }]}>
            <Input disabled style={{ width: 120 }} />
          </Form.Item>
          <Form.Item noStyle>
            <QuerySelect
              width={680}
              sysReportName="PartSearch"
              text={<FormattedMessage id="pages.select" />}
              title={<FormattedMessage id="pages.partNum" />}
              btntype="primary"
              setCurrent={setCurrentPart}
              scroll={{ x: 'max-content', y: '200px' }}
              params={{ InActive: 'false' }}
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        name={['model', 'partDescription']}
        label={<FormattedMessage id="pages.partDescription" />}
        rules={[{ required: true, message: intl.formatMessage({id: 'pages.partDescription.required'})  }]}
      >
        <Input disabled />
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.quantity" />}>
        <Input.Group compact>
          <Form.Item noStyle name={['model', 'ourQty']} rules={[{ required: true, message: intl.formatMessage({id: 'pages.quantity.required'}) }]}>
            <InputNumber
              min={0}
              max={maxQty}
              disabled={props.data?.receiptType == 'MTL' || props.data?.receiptType == 'JOB'}
            />
          </Form.Item>
          <Form.Item noStyle name={['model', 'ium']}>
            <Input
              style={{ width: 80 }}
              placeholder={intl.formatMessage({ id: 'pages.IUM' })}
              disabled
            />
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item
        name={['model', 'vendorUnitCost']}
        label={<FormattedMessage id="pages.unitCost" />}
        hidden
      >
        <InputNumber />
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="pages.inWarehouseCode" />}
        style={{ marginBottom: 0 }}
        tooltip={intl.formatMessage({ id: 'pages.warehouseTypeIsInspWhse' })}
      >
        <Input.Group compact>
          <WhseSelect
            width={120}
            rules={[
              { required: true, message: <FormattedMessage id="pages.warehouseCode.required" /> },
            ]}
            showSearch={true}
            name={['model', 'warehouseCode']}
            setCurrent={(e: any) => selectBin(e)}
            params={{ wType }}
            freshNum={freshNum}
          />
          <WhseBinSelect
            width={120}
            rules={[{ required: true, message: <FormattedMessage id="pages.binNum.required" /> }]}
            showSearch={true}
            name={['model', 'binNum']}
            placeholder={<FormattedMessage id="pages.inBinNum" />}
            params={params}
            freshNum={freshNum}
          />
        </Input.Group>
      </Form.Item>
      <Form.Item label={<FormattedMessage id="pages.lotNum" />} style={{ marginBottom: 0 }}>
        <Input.Group compact>
          <Form.Item name={['model', 'lotNum']}>
            <Input placeholder={intl.formatMessage({ id: 'pages.lotNum' })} disabled />
          </Form.Item>
          <Form.Item>
            <Button type="default" onClick={createLotNum}>
              <FormattedMessage id="pages.autoCreate" />
            </Button>
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: layout.labelCol.span }} style={{ marginBottom: 0 }}>
        <Input.Group compact>
          <Form.Item name={['model', 'receivedComplete']} valuePropName="checked">
            <Checkbox disabled>
              <FormattedMessage id="pages.received" />
            </Checkbox>
          </Form.Item>
          <Form.Item name={['model', 'inspectionReq']} valuePropName="checked">
            <Checkbox onChange={changeInsp}>
              <FormattedMessage id="pages.inspectionReq" />
            </Checkbox>
          </Form.Item>
        </Input.Group>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
        <Space>
          <Button
            key="1"
            type="primary"
            htmlType="submit"
            loading={loading}
            disabled={data?.receivedComplete}
          >
            <FormattedMessage id="pages.save" />
          </Button>
          <Button
            key="2"
            danger
            disabled={data?.id == undefined || data?.receivedComplete}
            onClick={delObj}
          >
            <FormattedMessage id="pages.delete" />
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
